package main

import (
	"fmt"
	"net"
)

func main() {

	listen, err := net.Listen("tcp", "127.0.0.1:9193")

	connections := make([]net.Conn, 10) //接收的连接

	//聊天信息管道
	messageChannels := make(chan string, 10)

	if err != nil {
		fmt.Println("tcp server connect error", err)
	}

	for { //外层循环处理多个连接

		conn, err := listen.Accept()
		if err != nil {
			fmt.Println("connection error", err)
		}

		for { //内层循环处理一个连接的多条消息
			buffer := make([]byte, 1024)
			_, err = conn.Read(buffer)

			if err != nil {
				fmt.Println("read content error")
			}

			//建立连接，将数据发送
			message := string(buffer)

			go readMessage(messageChannels, connections, conn)

			has := false

			//查看我有的连接是否包含当前连接
			for _, hasCon := range connections {
				if hasCon == conn {
					has = true
					break
				}
			}

			//如果不包含的话从0开始遍历连接找到为nil的连接把当前连接塞进去
			
			if !has {
				for key, value := range connections {
					if value == nil {
						connections[key] = conn
						break
					}
				}
			}

			//向所有人发送消息
			messageChannels <- message
		}
	}

}

func readMessage(channels chan string, connections []net.Conn, currentCon net.Conn) {

	message := <-channels

	for _, con := range connections {

		if con == nil || con == currentCon { //不给自己发
			continue
		}

		_, err := con.Write([]byte(message))

		if err != nil {
			fmt.Println("write message error", err)
		}

		//go func() {
		//	if err := con.Close(); err != nil {
		//		fmt.Println("error")
		//	}
		//}()
	}
}
